'use strict';

const db = uniCloud.database()
const $ = db.command.aggregate
const _ = db.command

exports.main = async (event, context) => {
  const { action, params = {} } = event
  
  switch (action) {
    case 'getHotStocks':
      return await getHotPatentCompanies(params)
      
    case 'searchStocks':
      return await searchStocks(params)
      
    case 'getStockDetail':  
      return await getStockDetail(params)
      
    default:
      return {
        code: 404,
        msg: '未找到对应的操作'
      }
  }
}

// 搜索股票
async function searchStocks({ keyword = '' }) {
  console.log('搜索关键词:', keyword)
  
  if (!keyword.trim()) {
    return {
      code: 200,
      msg: 'ok',
      data: { list: [] }
    }
  }

  try {
    const dbCmd = db.command
    
    const list = await db.collection('a_stocks')
      .where(dbCmd.or([
        {
          symbol: new RegExp(keyword, 'i')      // 股票代码
        },
        {
          name: new RegExp(keyword, 'i')        // 股票名称
        },
        {
          fullname: new RegExp(keyword, 'i')    // 公司全称
        },
        {
          cnspell: new RegExp(keyword, 'i')     // 拼音缩写
        }
      ]))
      .field({
        symbol: true,
        stock_code: true,  // 添加标准股票代码
        name: true,
        industry: true,
        area: true,
        market: true,
        fullname: true
      })
      .limit(10)
      .get()

    // 添加日志检查返回的数据
    console.log('搜索结果原始数据:', list.data)

    return {
      code: 200,
      msg: 'ok',
      data: {
        list: list.data.map(item => {
          // 确保 stock_code 存在，如果不存在则使用其他格式构造
          const stockCode = item.stock_code || `${item.symbol}.${item.market === '深圳' ? 'SZ' : 'SH'}`
          console.log('处理后的股票代码:', stockCode)
          
          return {
            code: item.symbol,
            stock_code: stockCode,
            name: item.name,
            industry: item.industry || '',
            area: item.area || '',
            market: item.market || '',
            fullname: item.fullname || '',
            patentCount: 0
          }
        })
      }
    }
  } catch (e) {
    console.error('搜索股票异常:', e)
    return {
      code: 500,
      msg: '搜索失败:' + e.message
    }
  }
}

// 获取热门股票
async function getHotStocks() {
  try {
    const list = await db.collection('a_stocks')
      .where({
        list_status: 'L',
        market: '主板'
      })
      .field({
        symbol: 1,
        name: 1,
        industry: 1,
        area: 1
      })
      .orderBy('list_date', 'desc')
      .limit(10)
      .get()
      .then(res => {
        return res.data.map(item => ({
          code: item.symbol,
          name: item.name,
          industry: item.industry || '',
          area: item.area || '',
          patentCount: 0
        }))
      })

    return {
      code: 200,
      msg: 'ok',
      data: { list }
    }

  } catch (e) {
    console.error('获取热门股票异常:', e)
    return {
      code: 500,
      msg: '获取数据失败'
    }
  }
}

// 添加获取专利热搜公司列表的函数
async function getHotPatentCompanies({ limit = 20 } = {}) {
  try {
    // 1. 获取访问次数最多的公司统计记录
    const statsResult = await db.collection('a_stock_patent_stats')
      .orderBy('api_call_count', 'desc')
      .limit(limit)
      .get()
    
    if (!statsResult.data.length) {
      return {
        code: 200,
        msg: 'ok',
        data: { list: [] }
      }
    }
    
    // 2. 获取这些公司的基本信息
    const stockCodes = statsResult.data.map(item => item.stock_code)
    const companiesResult = await db.collection('a_stocks')
      .where({
        stock_code: db.command.in(stockCodes)
      })
      .field({
        stock_code: true,
        name: true,
        fullname: true,
        industry: true,
        area: true
      })
      .get()
    
    // 3. 将公司信息和专利统计信息合并
    const companyMap = new Map(
      companiesResult.data.map(item => [item.stock_code, item])
    )
    
    const list = statsResult.data.map(stats => {
      const company = companyMap.get(stats.stock_code) || {}
      return {
        stock_code: stats.stock_code,
        name: company.name || '',
        fullname: company.fullname || '',
        industry: company.industry || '',
        area: company.area || '',
        patentCount: stats.total_count || 0,
        sampledCount: stats.sampled_count || 0,
        visitCount: stats.api_call_count || 0,
        lastUpdate: stats.update_time
      }
    })
    
    return {
      code: 200,
      msg: 'ok',
      data: { list }
    }
    
  } catch(e) {
    console.error('获取专利热搜公司列表异常:', e)
    return {
      code: 500,
      msg: '获取专利热搜公司列表失败:' + e.message
    }
  }
}

// 获取股票详情
async function getStockDetail({ code }) {
  try {
    if (!code) {
      return {
        code: 400,
        msg: '缺少股票代码'
      }
    }

    // 直接调用专利云函数获取专利信息
    const patentResult = await uniCloud.callFunction({
      name: 'patent',
      data: {
        action: 'getCompanyPatentInfo',
        params: {
          stockCode: code  // 直接使用传入的标准代码
        }
      }
    })

    return patentResult.result

  } catch (e) {
    console.error('获取股票详情异常:', e)
    return {
      code: 500,
      msg: '获取股票详情失败:' + e.message
    }
  }
}